import Vue from 'vue'
import Router from 'vue-router'
//
import HelloWorld from '@/components/HelloWorld'

Vue.use(Router)

const routes = [
  {
    path: '/',
    name: 'HelloWorld',
    component: HelloWorld
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/pages/login')
  },
  {
    path: '/layout',
    name: 'layout',
    component: () => import('@/pages/Layout'),
    children: [
      {
        path: '/home',
        name: 'home',
        meta: { title: '主页' },
        component: () => import('@/pages/home'),
        props: route => {
          const { query: { a }, ...rest } = route
          console.log('props', rest)
          return { a }
        },
        // 路由独享的守卫
        beforeEnter: (to, from, next) => {
          // ...
          next()
        }
      },
      {
        path: '/test',
        name: 'test',
        meta: { title: '测试' },
        component: () => import('@/pages/test'),
        props: route => ({ query: route.query })
      }
    ]
  }
]

const router = new Router({
  routes: [...routes, {
    path: '*',
    name: '404',
    component: () => import('@/pages/404')
  }],
  scrollBehavior (to, from, savedPosition) {
    // 期望滚动到哪个的位置
    if (savedPosition) {
      // 返回 savedPosition，在按下 后退/前进 按钮时，就会像浏览器的原生表现那样
      return savedPosition
    } else {
      return {
        x: 0,
        y: 0,
        // 只需将 behavior 选项添加到 scrollBehavior 内部返回的对象中
        // 就可以为支持它的浏览器 (https://developer.mozilla.org/en-US/docs/Web/API/ScrollToOptions/behavior)启用原生平滑滚动
        behavior: 'smooth'
      }
    }
    // 也可以返回一个 Promise 来得出预期的位置描述
    // return new Promise((resolve, reject) => {
    //   setTimeout(() => {
    //     resolve({ x: 0, y: 0 })
    //   }, 500)
    // })
  }
})

let isLogin = false
// 注册一个全局前置守卫
router.beforeEach((to, from, next) => {
  console.log('router beforeEach', to, from, isLogin)
  // next(false): 中断当前的导航
  // next(new Error())
  if (isLogin) {
    next()
  } else {
    isLogin = true
    next('login')
  }
})

// 全局后置钩子 (和守卫不同的是，这些钩子不会接受 next 函数也不会改变导航本身)
router.afterEach((to, from) => {
  // ...
})

export default router
